#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"agreement.h"
#include"clientSock.h"
#include"recivedata.h"
#include<QMessageBox>
#include<memory>
#include<iostream>
#include<QThread>
#include<QInputDialog>
#include<QWidget>
#include<QFileDialog>
#include<unistd.h>
#include<fstream>
#include<algorithm>
#include"transmissionpage.h"
#include<QTimer>
#include"loadform.h"
#include"MD5.h"
#include"fileprogress.h"


#define BufferSize 1024*20


void mainWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    Client::getInstance().stopThreadPool();
}

mainWindow::mainWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mainWindow)
{
    ui->setupUi(this);
    model.setStringList(friendList);
    ui->listView->setModel(&model);
    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::RefreshSignal,this,&mainWindow::RefreshFriend,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::AddFriendSignal,this,&mainWindow::AddFriend,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::CallBackFriendSignael,this,&mainWindow::FriendApply,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::RemeveFriend,this,&mainWindow::RemoveFriend,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::RemeveFriendREQ,this,&mainWindow::RemoveFriendREQ,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::SendMsgShow,this,&mainWindow::SendMsgShow,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::RefreshFileSignal,this,&mainWindow::showFileList,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::CreatNewFileSignal,this,&mainWindow::creatFileDir,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::DeleteFileSignal,this,&mainWindow::deletFile,Qt::QueuedConnection);

    QObject::connect(this,&mainWindow::startWindow,this,&mainWindow::startFileWindow,Qt::QueuedConnection);
    QObject::connect(this,&mainWindow::startDownWindow,this,&mainWindow::startDownFile,Qt::QueuedConnection);

    QObject::connect(&ReceiveData::getInstance(),&ReceiveData::FileACKMsg,this,&mainWindow::uploadAckc,Qt::QueuedConnection);


    layout = new QVBoxLayout(ui->widget);
    ui->widget->setLayout(layout);
    ui->tableWidget->horizontalHeader()->setVisible(true);
    ui->tableWidget->setSortingEnabled(true);

    fileDown = new FileProgress();


    // 启动超时检查定时器
    timer = new QTimer(nullptr);
    connect(timer, &QTimer::timeout, this, [this]() {
        // 在Lambda中调用实际的槽函数并传递参数
        checkAckForTimeouts();
    });
}

mainWindow::~mainWindow()
{
    // 释放 FriendScreen 中的 QTextEdit（若父组件为 nullptr）
    for (auto* widget : FriendScreen) {
        if (widget && !widget->parent()) { // 检查是否有父组件
            delete widget;
            widget = nullptr;
        }
    }
    FriendScreen.clear(); // 清空容器
    delete ui;
}


mainWindow &mainWindow::getInstance()
{
    static mainWindow instance;
    return instance;
}

void mainWindow::init(std::string name)
{
    userName = name;
    setWindowTitle(QString::fromStdString(userName));
    currentFilePath  = "./data/"+userName;
    rootDir = currentFilePath;
    loginRefresh();
}

void mainWindow::on_refreshFriend_clicked()
{
    CloudDrive::Packet pkt;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.type = CloudDrive::MessageType::REFRESH_FRIEND;
    pkt.header.timestamp = CloudDrive::now_millis();

    CloudDrive::UserInfo uIfo;
    strncpy(uIfo.account,userName.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);

    Client::getInstance().sendData(CloudDrive::makeUserPacket(pkt,uIfo,0));
}

void mainWindow::RefreshFriend(QStringList frienlist)
{

    for(int i = 0;i<frienlist.size();i++){
        if(friendList.count(frienlist[i])==0){
            std::lock_guard<std::mutex> look(friendMutex);
            friendList.append(frienlist[i]);
            QTextEdit *chatWindow = new QTextEdit();
            chatWindow->setFixedWidth(400);
            chatWindow->setFixedHeight(311);
            chatWindow->setReadOnly(true);
            FriendScreen[frienlist[i]] = chatWindow;
        }
    }
    model.setStringList(friendList);
    ui->listView->update();
}

void mainWindow::loginRefresh()
{
    QThread::msleep(50);
    on_refreshFriend_clicked();
    QThread::msleep(50);
    on_refreshFile_clicked();
}

void mainWindow::uploadFile(std::string sendName,std::string recName,QString fileName, std::shared_ptr<CloudDrive::UploadControl> contral,CloudDrive::Packet &pkt,int flag)
{
    std::function<void()> task = [this,sendName,recName,fileName,contral,pkt,flag](){
        QFile file(fileName);
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "无法打开文件:" << file.errorString();
            return;
        }
        // 获取文件名(用于显示)
        QString filename = QFileInfo(fileName).fileName();

        // 获取文件大小
        size_t fileSize = file.size();

        //发送数据
        std::vector<char> buffer(BufferSize);
        size_t totalSent = 0; //发送的数据量
        int currId;
        if(0 == flag)//上传
        {
            currId = totalSubuploadWindow.fetch_add(1);
            std::lock_guard<std::mutex> lock(windConMutex);
            windowContral[currId] = contral;
            emit startWindow(currId,filename.toStdString(),contral);
            totalSubuploadWindow++;
        }

        uint32_t id = 0;

        while(totalSent<fileSize){
            //构建请求头
            CloudDrive::Packet pkt1 = pkt;
            pkt1.header.timestamp = CloudDrive::now_millis();
            {
                std::unique_lock<std::mutex> lk(contral->mtx);
                contral->cv.wait(lk,[&](){ return !contral->paused || contral->cancelled;});
                if(contral->cancelled){
                    qDebug()<<"上传取消";
                    file.close();
                    return;
                }
            }
            //判断剩余数据量和要读取的数据量的大小
            size_t bytesToRead = std::min(static_cast<size_t>(BufferSize),fileSize-totalSent);
            size_t bytesRead = file.read(buffer.data(),bytesToRead);

            if(static_cast<int>(bytesRead) == -1){
                qDebug()<<"文件读取失败";
                break;
            }

            //发送数据
            bool sendSuccess = false;
            int retryCount = 3;
            while (retryCount >0 && !sendSuccess) {
                try {
                    std::vector<uint8_t> data(buffer.begin(), buffer.begin() + bytesRead);
                    {
                        CloudDrive::FileInfoSave fiSave = CloudDrive::makeFileDataSave(sendName,recName,filename.toStdString(),
                                                                                       currentFilePath,fileSize,bytesRead,totalSent,id,"",data);

                        std::lock_guard<std::mutex> lk(fileDataMutex);
                        fileData.emplace(std::make_pair(filename.toStdString(),id),fiSave);
                    }
//                    qDebug()<<"dou"<<filename;
                    Client::getInstance().sendData(CloudDrive::makeFilePacket(pkt,sendName,recName,filename.toStdString(),
                                                                              currentFilePath,fileSize,bytesRead,totalSent,id,"",data,3));
                    QThread::msleep(20);
                    sendSuccess = true;
                } catch (const std::exception & e) {
                    retryCount--;
                    // 短暂延迟后重试
                    std::cout<<"error\t"<<e.what()<<std::endl;
                    std::this_thread::sleep_for(std::chrono::milliseconds(500));
                }
            }

            if(0 == fileSize) break;

            if(!sendSuccess) {
                qDebug()<<"发送失败，已达到最大重试次数";
                break;
            }

            totalSent += bytesRead;
            id++;
            //上传
            if(0==flag){
               emit ProgressBar(currId,static_cast<double>(totalSent)/fileSize*100);
            }

        }
        file.close();
//        totalSubWindow.fetch_add(1, std::memory_order_relaxed);
    };

    Client::getInstance().addFunc(task);
}

void mainWindow::on_addFriend_clicked()
{
    std::string friendPhone = ui->addFriendName->text().toStdString();
    if(friendPhone.empty()) return;
    if(friendList.contains(QString::fromStdString(friendPhone))){
        QMessageBox::information(this,"添加好友","好友存在无需重复添加");
        ui->addFriendName->clear();
        return;
    }
    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::ADD_FRIEND;
    pkt.header.version = CloudDrive::now_millis();
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;

    CloudDrive::UserInfo uIfo;
    std::memcpy(uIfo.account,userName.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    std::memcpy(uIfo.friendName,friendPhone.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    ui->addFriendName->clear();
    Client::getInstance().sendData(CloudDrive::makeUserPacket(pkt,uIfo,0));
}

void mainWindow::AddFriend(CloudDrive::MessageReturn type)
{
    try {
        switch (type) {
        case CloudDrive::MessageReturn::ADDFRIEND_NOTEXIST:{
            QMessageBox::information(this,"添加好友","用户不存在或不在线");
            break;
        }
        case CloudDrive::MessageReturn::ADDFRIEND_NOTAGREE:{
            QMessageBox::information(this,"添加好友","对方不同意");
            break;
        }
        case CloudDrive::MessageReturn::ADDFRIEND_AGREE:{
            QMessageBox::information(this,"添加好友","成功添加好友");
            break;
        }
        default:{
            break;
        }
        }
        on_refreshFriend_clicked();
    } catch (const std::exception& e) {
        // 捕获标准异常
//        qCritical() << "Standard exception caught:" << e.what();
    }
}

void mainWindow::FriendApply(std::string str)
{
    std::string userName1 = "用户"+str+"请求添加好友";

    QMessageBox::StandardButton ret = QMessageBox::information(this,"添加好友",QString::fromStdString(userName1),QMessageBox::Ok|QMessageBox::No);
    CloudDrive::UserInfo msgback;
    if(ret == QMessageBox::Ok){
        msgback.type = CloudDrive::MessageReturn::ADDFRIEND_AGREE;
    }
    else {
        msgback.type = CloudDrive::MessageReturn::ADDFRIEND_NOTAGREE;
    }
    std::memcpy(msgback.account,userName.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    std::memcpy(msgback.friendName,str.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);

    CloudDrive::Packet pkt;
    pkt.header.type=CloudDrive::MessageType::ADD_FRIEND_REQ;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.timestamp = CloudDrive::now_millis();
    Client::getInstance().sendData(CloudDrive::makeUserPacket(pkt,msgback,0));
}

void mainWindow::RemoveFriend(CloudDrive::MessageReturn type)
{
    if(type == CloudDrive::MessageReturn::DELETE_FRIEND_OK){
        QMessageBox::information(this,"删除好友","好友删除成功");
        std::lock_guard<std::mutex> lock(friendMutex);
        //从布局中也删除
        //从布局中也删除
        while (QLayoutItem* item = layout->takeAt(0)) {
            if (item->widget()) {
                item->widget()->setVisible(false);
            }
            delete item;
        }
        // 从列表和映射中移除好友
        if (friendList.contains(currentFriend)) {
            friendList.removeOne(currentFriend);
        }

        if (FriendScreen.contains(currentFriend)) {
            FriendScreen.remove(currentFriend);
        }
        model.setStringList(friendList);
        ui->listView->update();
    }
    else{
        QMessageBox::information(this,"删除好友","好友删除失败");
    }
}

void mainWindow::RemoveFriendREQ(CloudDrive::MessageReturn type,std::string str)
{
    try {
        if(type == CloudDrive::MessageReturn::DELETE_FRIEND_OK){
            std::lock_guard<std::mutex> lock(friendMutex);
            QString strName =QString::fromStdString(str);
            QTextEdit * edit = FriendScreen[strName];

            // 安全检查layout是否为空
            if (layout->count() > 0) {
                // 保存第一个项目的指针，避免多次调用takeAt(0)
                QLayoutItem* firstItem = layout->itemAt(0);
                if (firstItem && !firstItem->isEmpty() && firstItem->widget() == edit) {
                    // 清空布局
                    while (QLayoutItem* item = layout->takeAt(0)) {
                        if (item->widget()) {
                            item->widget()->setVisible(false);
                        }
                        delete item;
                    }
                }
            }

            // 从列表和映射中移除好友
            if (friendList.contains(strName)) {
                friendList.removeOne(strName);
            }

            if (FriendScreen.contains(strName)) {
                FriendScreen.remove(strName);
            }
            if(currentFriend == strName){
                currentFriend = "";
            }
            edit = nullptr;
            model.setStringList(friendList);
            ui->listView->update();
        }
    } catch (const std::exception& e) {
        // 捕获标准异常
        qCritical() << "Standard exception caught:" << e.what();
    }
}

void mainWindow::SendMsgShow(std::string friendName, std::string msg)
{
    QString fName = QString::fromStdString(friendName);
    if(friendList.contains(fName) == 0) return;
    QTextEdit * chatWindow = FriendScreen[fName];
    chatWindow->setTextColor(QColor("#008000"));
    chatWindow->append(QString::fromStdString(msg));
    chatWindow->setAlignment(Qt::AlignLeft);
}

void mainWindow::showFileList(CloudDrive::MesBackFile fileListInfo)
{
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(fileListInfo.FileNum);
    for(int i = 0;i<static_cast<int32_t>(fileListInfo.FileNum);i++){
        // 使用new在堆上创建对象
        QTableWidgetItem *itemName = new QTableWidgetItem(fileListInfo.fileInfo[i].fileName);
        ui->tableWidget->setItem(i, 0, itemName);

        // 可以继续设置其他列
        QTableWidgetItem *itemData = new QTableWidgetItem(fileListInfo.fileInfo[i].fileData);
        ui->tableWidget->setItem(i, 1, itemData);

        QString fileType;
        QTableWidgetItem *itemSize = new QTableWidgetItem(QString::number(fileListInfo.fileInfo[i].fileSize)+"kb");
        if(std::strcmp(fileListInfo.fileInfo[i].fileType,"dir") == 0){
             fileType = "文件夹";
             itemSize->setText("");
        }
        else{
            std::string nameFile = fileListInfo.fileInfo[i].fileName;
            fileType = QString::fromStdString(nameFile.substr(nameFile.find_last_of('.')+1,nameFile.size()-nameFile.find_last_of('.')))+"文件";
        }
        QTableWidgetItem *itemType = new QTableWidgetItem(fileType);
        ui->tableWidget->setItem(i, 2, itemType);
        ui->tableWidget->setItem(i, 3, itemSize);
//        std::cout << "fileName:" << fileListInfo.fileInfo[i].fileName
//                  << "\t filedata:" << fileListInfo.fileInfo[i].fileData
//                  << "\t filesize:" << fileListInfo.fileInfo[i].fileSize
//                  << "\t type:" << fileListInfo.fileInfo[i].fileType
//                  << std::endl;
    }
//    ui->tableWidget->sortItems(2,Qt::DescendingOrder);

}

void mainWindow::creatFileDir(CloudDrive::MessageReturn type)
{
    if(type == CloudDrive::MessageReturn::NEW_DIR_EXIST){
        QMessageBox::information(this,"新建文件夹","文件夹存在");
    }
    else if(type == CloudDrive::MessageReturn::NEW_DIR_NO){
        QMessageBox::information(this,"新建文件夹","新建文件夹失败");
    }
    else {
        QMessageBox::information(this,"新建文件夹","新建文件夹成功");
        on_refreshFile_clicked();
    }
}

void mainWindow::deletFile(CloudDrive::MessageReturn type)
{
    if(type == CloudDrive::MessageReturn::DELETE_FILE_NOTEXIST){
        QMessageBox::information(this,"删除文件夹","文件夹不存在");
    }
    else if(type == CloudDrive::MessageReturn::DELETE_FILE_NO){
        QMessageBox::information(this,"删除文件夹","文件删除失败");
    }
    else {
        QMessageBox::information(this,"删除文件夹","删除文件夹成功");
        on_refreshFile_clicked();
    }
}

void mainWindow::uploadAckc(CloudDrive::FileInfo fileInfo)
{
    std::string name = fileInfo.filename;
    int id = fileInfo.dataBlockId;

    {
        std::lock_guard<std::mutex> lk(fileDataMutex);
        auto it = fileData.find(std::make_pair(name,id));
        if(it != fileData.end()){
            qDebug()<<it->second.dataBlockId;
            fileData.erase(it);
        }
        else {
             qDebug()<<"shangchu1\t"<<QString::fromStdString(name)<<"\tid"<<id;
        }
    }
}

void mainWindow::checkAckForTimeouts()
{
    std::lock_guard<std::mutex> lk(fileDataMutex);
    auto now = std::chrono::steady_clock::now();
    for(auto it = fileData.begin();it != fileData.end(); it++){
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - it->second.dataTime).count();
        if(elapsed>1000){//超时时间为1000ms
            CloudDrive::Packet pkt;
            pkt.header.version = CloudDrive::PROTOCOL_VERSION;
            pkt.header.timestamp = CloudDrive::now_millis();
            pkt.header.type = CloudDrive::MessageType::UPLOADFILE;
            Client::getInstance().sendData(CloudDrive::makeFilePacket(pkt,it->second.sendName,it->second.recName,it->second.filename,
                                                                      it->second.filePath,it->second.total_size,
                                                                      it->second.chunk_size,it->second.offset,it->second.dataBlockId,
                                                                      "",it->second.data,3));
            qDebug()<<"chong\t"<<it->second.filename<<"\tid:"<<it->second.dataBlockId;
            QThread::msleep(10);
        }

    }
}

void mainWindow::startDownFile(int id,std::string fileIdenter, std::string fileName)
{
    loadForm *downWindow = new loadForm(id,fileIdenter,fileName);
    qDebug()<<"window"<<QString::fromStdString(fileIdenter);
    QObject::connect(fileDown,&FileProgress::FunishDownFile,downWindow,&loadForm::setProgressBar,Qt::QueuedConnection);
    downWindow->setAttribute(Qt::WA_DeleteOnClose);//可以避免内存泄露
    downWindow->show();
}

void mainWindow::startFileWindow(int i,std::string name,std::shared_ptr<CloudDrive::UploadControl> contral)
{
    //构建窗体
    TransmissionPage *loadWindow = new TransmissionPage(i,contral);
    loadWindow->setAttribute(Qt::WA_DeleteOnClose);
    loadWindow->show();
    loadWindow->setFileName(name);
}

void mainWindow::startFileUploadFunish(int id,std::string filepath)
{
    std::lock_guard<std::mutex> lk(windConMutex);
    {
        if(windowContral.count((id)!=0)){
            std::shared_ptr<CloudDrive::UploadControl> contral = windowContral[id];
            windowContral.erase(id);
        }
    }

    CloudDrive::Packet pkt;
    pkt.header.timestamp = CloudDrive::now_millis();
    pkt.header.type = CloudDrive::MessageType::UPLOADFILE_FUNISH;
    CloudDrive::FileInfo fi;
    std::string str = currentFilePath +"/" +filepath;
    std::memcpy(&fi.filename,filepath.c_str(),CloudDrive::MAX_FILENAME_LEN-1);
    std::memcpy(&fi.filePath,str.c_str(),CloudDrive::MAX_FILENAME_LEN-1);

    Client::getInstance().sendData(CloudDrive::makeFileInfoPacket(pkt,fi,3));
    qDebug()<<QThread::currentThreadId()<<QString::fromStdString(str);
    QThread::msleep(1);
    on_refreshFile_clicked();
}

// 切换对话框
void mainWindow::on_listView_doubleClicked(const QModelIndex &index)
{
    if(!index.isValid()) return;

    QString friendName = index.data(Qt::DisplayRole).toString();
    currentFriend = friendName;
    // 移除当前布局中的所有窗口
    while (QLayoutItem* item = layout->takeAt(0)) {
        if (item->widget()) {
            item->widget()->setVisible(false);
        }
        delete item;
    }
    // 添加选中好友的聊天窗口
    QTextEdit* chatWindow = FriendScreen[friendName];
    layout->addWidget(chatWindow);
    chatWindow->setVisible(true);
}

void mainWindow::on_deletFriend_clicked()
{
    if(currentFriend.isEmpty()) return;
    QMessageBox::StandardButton ret = QMessageBox::information(this,"删除好友","是否删除好友"+currentFriend,QMessageBox::Ok|QMessageBox::No);

    if(ret == QMessageBox::No) return;

    CloudDrive::Packet pkt;
    pkt.header.type=CloudDrive::MessageType::REMOVE_FRIEND;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.timestamp=CloudDrive::now_millis();

    CloudDrive::UserInfo uIfo = CloudDrive::makeUserInfo(userName,"","","",currentFriend.toStdString(),CloudDrive::MessageReturn::LOGIN_NO);

    pkt = CloudDrive::makeUserPacket(pkt,uIfo,0);

    Client::getInstance().sendData(pkt);

}
//发送消息
void mainWindow::on_sendMsg_clicked()
{
    std::string msg = ui->plainTextEdit->toPlainText().toStdString();
    if(msg.empty() | currentFriend.toStdString().empty()){
        ui->plainTextEdit->clear();
        return;
    }
    CloudDrive::UserInfoMsg uIfoMsg;
    std::memcpy(uIfoMsg.account,userName.c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    std::memcpy(uIfoMsg.friendName,currentFriend.toStdString().c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    std::memcpy(uIfoMsg.msg,msg.c_str(),CloudDrive::MAX_MESSAGE_LEN-1);

    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::SEND_FRIEND_MSG;
    Client::getInstance().sendData(CloudDrive::makeUserMsgPacket(pkt,uIfoMsg,1));
    QTextEdit * chatWindow = FriendScreen[currentFriend];
    chatWindow->setTextColor(Qt::black);
    chatWindow->append(QString::fromStdString(msg));
    chatWindow->setAlignment(Qt::AlignRight);
    ui->plainTextEdit->clear();
}

// 刷新文件列表
void mainWindow::on_refreshFile_clicked()
{
    if(currentFilePath.empty()) return;
    CloudDrive::UserInfoMsg uIfomsg;
    qDebug()<<QString::fromStdString(currentFilePath);
    std::memcpy(uIfomsg.msg,currentFilePath.c_str(),CloudDrive::MAX_MESSAGE_LEN-1);

    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::REFRESH_FILELIST;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.timestamp = CloudDrive::now_millis();

    Client::getInstance().sendData(CloudDrive::makeUserMsgPacket(pkt,uIfomsg,2));

}

void mainWindow::on_tableWidget_cellActivated(int row, int column)
{
    Q_UNUSED(column);
    qDebug()<<ui->tableWidget->item(row,2)->text();
    if(ui->tableWidget->item(row,2)->text() == "文件夹"){
        currentFilePath = currentFilePath+"/"+ui->tableWidget->item(row,0)->text().toStdString();
        on_refreshFile_clicked();
    }
}

void mainWindow::on_upFIle_clicked()
{
    if(currentFilePath == rootDir) return;
    std::string supDir = currentFilePath.substr(0,currentFilePath.find_last_of('/'));
    qDebug()<<QString::fromStdString(supDir);
    currentFilePath = supDir;
    on_refreshFile_clicked();
}

void mainWindow::on_newDir_clicked()
{
    bool ok = false;
    QString text =  QInputDialog::getText(this,"新建文件夹","文件名称",QLineEdit::Normal,"",&ok);
    if(!ok | text.isEmpty()) return;
    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::NEWFILEDIR;
    pkt.header.timestamp = CloudDrive::now_millis();
    pkt.header.version =CloudDrive::PROTOCOL_VERSION;

    CloudDrive::UserInfoMsg uIfo;
    std::memcpy(uIfo.account,text.toStdString().c_str(),CloudDrive::MAX_ACCOUNT_LEN-1);
    std::string path = currentFilePath + '/'+text.toStdString();
    std::memcpy(uIfo.msg,path.c_str(),CloudDrive::MAX_MESSAGE_LEN);

    Client::getInstance().sendData(CloudDrive::makeUserMsgPacket(pkt,uIfo,0));
}

void mainWindow::on_deleteFile_clicked()
{
    if(curSelectFile.empty()) return;
    QMessageBox::StandardButton ret = QMessageBox::information(this,"删除文件","是否删除文件"+QString::fromStdString( curSelectFile),QMessageBox::Ok|QMessageBox::No);
    if(ret == QMessageBox::No) return;
    CloudDrive::UserInfoMsg fileInfo;
    std::string path = currentFilePath+"/"+curSelectFile;
    std::strncpy(fileInfo.msg,path.c_str(),CloudDrive::MAX_MESSAGE_LEN-1);

    CloudDrive::Packet pkt;
    pkt.header.type = CloudDrive::MessageType::DELETEFILE;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.timestamp = CloudDrive::now_millis();

    Client::getInstance().sendData(CloudDrive::makeUserMsgPacket(pkt,fileInfo,1));
}

// 单击选中
void mainWindow::on_tableWidget_cellClicked(int row, int column)
{
    Q_UNUSED(column);
    curSelectFile = ui->tableWidget->item(row,0)->text().toStdString();
    qDebug()<<QString::fromStdString(curSelectFile);
}
// 点击空白位置清除
void mainWindow::on_tableWidget_itemSelectionChanged()
{
    QList<QTableWidgetItem*> selectedItems = ui->tableWidget->selectedItems();
    if (selectedItems.isEmpty()) {
        curSelectFile.clear();
    }
}
// 上传文档
void mainWindow::on_loadFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,"选择文件",QDir::currentPath(),"所有文件 (*)");
    if(fileName.isEmpty()) return;

    auto contral = std::make_shared<CloudDrive::UploadControl>();

    CloudDrive::Packet pkt;
    pkt.header.version = CloudDrive::PROTOCOL_VERSION;
    pkt.header.type = CloudDrive::MessageType::UPLOADFILE;

    uploadFile("","",fileName,contral,pkt,0);

    timer->start(200); // 每100毫秒检查一次超时
}

void mainWindow::on_downFile_clicked()
{
    std::string fileName = curSelectFile;
    if(fileName.empty()) return;
    QMessageBox::StandardButton ret = QMessageBox::information(this,"下载文件","是否下载文件"+QString::fromStdString(fileName),QMessageBox::Ok|QMessageBox::No);
    if(ret == QMessageBox::No) return;

    CloudDrive::Packet pkt = CloudDrive::makePacket(CloudDrive::MessageType::DOWNFILE);
    CloudDrive::FileInfo fi;
    std::strncpy(fi.filePath,currentFilePath.c_str(),CloudDrive::MAX_MESSAGE_LEN-1);

    std::strncpy(fi.filename,fileName.c_str(),CloudDrive::MAX_FILENAME_LEN-1);
    std::string fileIdenter = md5Encrypt(QString::fromStdString(userName+fileName+ std::to_string(CloudDrive::now_millis()))).toStdString();
//    qDebug()<<"fi"<<fileIdenter.size();
    std::strncpy(fi.fileIdentfir,fileIdenter.c_str(),CloudDrive::MAX_FILEIDENTER_LEN-1);


    Client::getInstance().sendData(CloudDrive::makeFileInfoPacket(pkt,fi,4));
    int id = totalSubdownWindow.fetch_add(1);
    emit startDownWindow(id,fileIdenter,fileName);
    id++;
}









